
function Promise(executor) {
    this.PromiseState = 'pending';
    this.PromiseResult = undefined;
    this.callbacks = [];
    let resolve = (value) => {
        if (this.PromiseState !== 'pending') return;
        this.PromiseState = 'fulfilled';
        this.PromiseResult = value;
        if (this.callbacks.length) {
            this.callbacks.forEach(item => {
                item.success();
            })
        }
    }
    let reject = (reason) => {
        if (this.PromiseState !== 'pending') return;
        this.PromiseState = 'rejected';
        this.PromiseResult = reason;
        if (this.callbacks.length) {
            this.callbacks.forEach(item => {
                item.fail();
            })
        }
    }
    try {
        executor(resolve, reject);
    } catch (e) {
        reject(e);
    }
}
Promise.prototype.then = function (onResolved, onRejected) {
    // 函数内部自己调用自己：递归调用
    return new Promise((resolve, reject) => {
        let changeState = (typeFn) => {
            let rs = typeFn(this.PromiseResult);
            if (rs instanceof Promise) {
                rs.then(resolve, reject);
            } else {
                resolve(rs);
            }
        }
        if (this.PromiseState === 'fulfilled') {
            changeState(onResolved);
        }
        if (this.PromiseState === 'rejected') {
            changeState(onRejected);
        }
        if (this.PromiseState === 'pending') {
            this.callbacks.push({
                success: () => {
                    changeState(onResolved);
                },
                fail: () => {
                    changeState(onRejected);
                }
            })
        }
    })
}